﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Web.Mvc;
using BLL.Services;
using BLL.Services.Responses;
using BLL.Services.Responses.Listing;
using MvcContrib.Sorting;
using MvcContrib.UI.Grid;
using Web.Areas.Admin.Infrastructure;
using Web.Areas.Admin.Models.Responses;
using Web.Infrastructure;
using Web.Infrastructure.Models;
using Web.Infrastructure.Security;

namespace Web.Areas.Admin.Controllers
{
    /// <summary>
    /// Responses Controller
    /// </summary>
    [AdminAuthorization]
    public partial class ResponsesController : AdminController
    {
        private readonly IResponsesService _responsesService;

        /// <summary>
        /// Initializes a new instance of the <see cref="ResponsesController" /> class.
        /// </summary>
        /// <param name="responsesService">The responses service.</param>
        public ResponsesController(IResponsesService responsesService)
        {
            _responsesService = responsesService;
        }

        public virtual ActionResult Index()
        {
            return BackBoneView(MVC.Admin.Shared.Views.Empty);
        }

        public virtual ActionResult ListingTemplate()
        {
            return BackBoneView(MVC.Admin.Responses.Views.Listing);
        }

        [ListingAction("UserEmail")]
        public virtual ActionResult Listing(GridSortOptions sort, int size, int page, ResponseFilter filter)
        {
            var model = _responsesService.GetListingResponse(
                page, size, sort.Column, sort.Direction != SortDirection.Descending ? 0 : 1, filter);
            return BackBoneJson(model);
        }

        public virtual ActionResult Delete(int[] items)
        {
            var model = new BaseModel();
            foreach (var item in items)
            {
                try
                {
                    _responsesService.Delete(item);
                }
                catch (ServiceException exception)
                {
                    ModelState.AddModelError(string.Empty, "Could not delete response with id " + item);
                    Trace.TraceError(exception.ToString());
                }
            }
            model.Errors = GetErrors;
            if (ModelState.IsValid)
            {
                model.SuccessMessage = "Response have been deleted successfully";
            }
            return Json(model);
        }

        [HttpGet]
        public virtual ActionResult Create()
        {
            return BackBoneView(MVC.Admin.Shared.Views.Empty);
        }

        public virtual ActionResult CreateTemplate()
        {
            return BackBoneView(MVC.Admin.Responses.Views.Create, new ResponseCreateModel());
        }

        [HttpPost]
        public virtual ActionResult Create(ResponseCreateModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Errors = GetErrors;
                return Json(model);
            }
            var response = (Response)model;
            try
            {
                _responsesService.Create(response);
                model.SuccessMessage = "Responses has been created successfully.";
                return Json(model);
            }
            catch (ServiceException exception)
            {
                ModelState.AddModelError(string.Empty, exception.Message);
                model.Errors = GetErrors;
                return Json(model);
            }
        }

        [HttpGet]
        public virtual ActionResult Edit(int? responseId)
        {
            var model = new ResponseEditModel();
            if (!responseId.HasValue)
            {
                model.Errors = new List<ErrorModel>
                    {
                        new ErrorModel("Empty value.")
                    };
                return BackBoneJson(model);
            }
            var response = _responsesService.GetResponseById(responseId.Value);

            if (response == null)
            {
                model.Errors = new List<ErrorModel>
                    {
                        new ErrorModel(string.Format("Response {0} was not found", responseId))
                    };
                return BackBoneJson(new ResponseEditModel());
            }
            model = new ResponseEditModel(response);
            return BackBoneJson(model);
        }

        public virtual ActionResult EditTemplate()
        {
            return PartialView(MVC.Admin.Responses.Views.Edit, new ResponseEditModel());
        }

        [HttpPost]
        public virtual ActionResult Edit(int responseId, ResponseEditModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Errors = GetErrors;
                return Json(model);
            }
            var response = (Response)model;
            try
            {
                _responsesService.Save(response);
                model.SuccessMessage = "Response has been successfully updated.";
                return Json(model);
            }
            catch (ServiceException exception)
            {
                ModelState.AddModelError(string.Empty, exception.ToString());
                model.Errors = GetErrors;
                Json(model);
            }
            return BackBoneJson(model);
        }
    }
}